package com.seculab.common.util;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.UUID;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.multipart.MultipartHttpServletRequest;

import com.seculab.common.domain.Attachment;

public class FileUploadUtil {
	private static Logger logger = LoggerFactory.getLogger(FileUploadUtil.class);
	
	public static List<Attachment> upload(HttpServletRequest request) throws Exception {
		MultipartHttpServletRequest multiRequest = (MultipartHttpServletRequest)request;
		Map<String, MultipartFile> files = multiRequest.getFileMap();
		logger.debug("{}", "file size is " + files.size());
		String realPath = "c:\\temp";
		MultipartFile file;
		Iterator<Entry<String, MultipartFile>> iter = files.entrySet().iterator();
		List<Attachment> fileList = new ArrayList<Attachment>();
		Attachment attachment = null;
		String sysFileName = null;
		
		if(iter.hasNext()) {
			Entry<String, MultipartFile> entry = iter.next();
			file = entry.getValue();

			if(file.getSize() > 0) {
				sysFileName = FileUploadUtil.uploadFile(file, realPath);
				attachment = new Attachment();
				attachment.setFilePath(realPath);
				attachment.setFileSize(file.getSize());
				attachment.setOriginFileName(file.getOriginalFilename());
				attachment.setSysFileName(sysFileName);
				fileList.add(attachment);
			}
		}
		
		return fileList;
	}	
	
	public static List<Attachment> upload(Map<String, MultipartFile> files) throws Exception {
		String realPath = "c:\\temp";
		MultipartFile file;
		Iterator<Entry<String, MultipartFile>> iter = files.entrySet().iterator();
		List<Attachment> fileList = new ArrayList<Attachment>();
		Attachment attachment = null;
		String sysFileName = null;
		
		if(iter.hasNext()) {
			Entry<String, MultipartFile> entry = iter.next();
			file = entry.getValue();
			
			if(file.getSize() > 0) {
				sysFileName = FileUploadUtil.uploadFile(file, realPath);
				attachment = new Attachment();
				attachment.setFilePath(realPath);
				attachment.setFileSize(file.getSize());
				attachment.setOriginFileName(file.getOriginalFilename());
				attachment.setSysFileName(sysFileName);
				fileList.add(attachment);
			}
		}
		
		return fileList;
	}
	
	public static void upload(Map<String, MultipartFile> files, String realPath) throws Exception {
		MultipartFile file;
		Iterator<Entry<String, MultipartFile>> iter = files.entrySet().iterator();
		
		if(iter.hasNext()) {
			Entry<String, MultipartFile> entry = iter.next();
			file = entry.getValue();
			
			FileUploadUtil.uploadFile(file, realPath);
		}
	}	
	
	public static String uploadFile(MultipartFile formFile, String realPath) throws Exception {
        String tempFileName = UUID.randomUUID().toString().replaceAll("-", "") + "." + StringUtils.getExtension(formFile.getOriginalFilename());
        OutputStream bos = null;
        InputStream stream = null;
        
        try {
            stream = formFile.getInputStream();

            bos = new FileOutputStream(realPath + "\\" + tempFileName);
            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = stream.read(buffer, 0, 8192)) != -1) {
                bos.write(buffer, 0, bytesRead);
            }

            logger.info("{}", "The file has been written to \"" + realPath + tempFileName);
            return tempFileName;
        } catch (FileNotFoundException e) {
            throw e;
        } catch (IOException e) {
        	throw e;
        } finally {
            if(bos != null) try {bos.close();} catch(Exception e) {}
            if(stream != null) try{stream.close();} catch(Exception e) {}
        }
    }
	
}
